<?php

namespace App\Containers\AppSection\Accreditation\Actions;

use App\Containers\AppSection\Accreditation\Tasks\CreateRemarkTask;
use App\Containers\AppSection\Accreditation\Tasks\DeleteAllRemarksByAccreditationIdTask;
use App\Containers\AppSection\Accreditation\Tasks\FindAccreditationByIdTask;
use App\Containers\AppSection\Accreditation\Tasks\UpdateAccreditationTask;
use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Profile\Tasks\UpdateProfileTask;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Requests\Request;

class ModeratorCheckAccreditationAction extends Action
{

    public function run($id, Request $request)
    {
        $accreditation = app(FindAccreditationByIdTask::class)->run($id);

        app(DeleteAllRemarksByAccreditationIdTask::class)->run($accreditation->id);

        if (!empty($request->getInputByKey('remarks'))) {
            foreach ($request->getInputByKey('remarks') as $remark) {
                app(CreateRemarkTask::class)->run([
                    'message' => $remark,
                    'accreditation_id' => $accreditation->id,
                    'profile_id' => $request->profile()->id
                ]);
            }
        }

        $accreditedAt = null;
        if ($request->getInputByKey('type') === 'accreditation_accredited') {
            $accreditedAt = now();
        }

        app(UpdateProfileTask::class)->run($accreditation->profile->id, [
            'accreditation_status_key' => $request->getInputByKey('type'),
            'accredited_at' => $accreditedAt
        ]);

        app(UpdateAccreditationTask::class)->run($accreditation->id, [
            'moderator_id' => $request->profile()->id
        ]);

        $log = '';
        switch ($request->getInputByKey('type')) {
            case 'accreditation_accredited':
                $log = "Профиль №{$accreditation->profile->id} аккредитован";
                break;
            case 'accreditation_returned':
                $log = "Профиль №{$accreditation->profile->id} отправлен на доработку";
                break;
            case 'accreditation_rejected':
                $log = "Профиль №{$accreditation->profile->id} отклонен";
                break;
        }

        app(UpdateAccreditationTask::class)->run($accreditation->id, ['updated_at' => now()]);

        app(CreateLogTask::class)->run($accreditation->profile->id, $log . ' (модератор)', 'accreditation', $accreditation->id);
        app(CreateLogTask::class)->run($request->profile()->id, $log, 'accreditation', $accreditation->id);
    }
}
